// 1. 引入依赖（不变）
const db = uniCloud.database()
const dbCmd = db.command
const {
	generateString
} = require('linliUtils')

// 关系状态常量（不变）
const RELATION_STATUS = {
	APPLYING: 0,
	FRIEND: 1,
	BLOCKED: 2,
	DELETED: 3
};

class FriendService {
	constructor() {
		this.db = db;
		this.dbCmd = dbCmd;
		this.relationCollection = db.collection('friendRelation');
		this.userCollection = db.collection('linli-user');
		this.noticeCollection = db.collection('friend_notice');
	}

	// 通用参数校验（不变）
	validateParams(params, requiredKeys) {
		console.log("参数检验。。。。。。", params, requiredKeys);
		for (const key of requiredKeys) {
			if (params[key] === undefined || params[key] === null) {
				throw new Error(`参数错误：${key} 不能为空`);
			}
		}
	}
	// 状态码转文本（不变）
	getStatusText(status) {
		const statusMap = {
			[RELATION_STATUS.APPLYING]: '发送申请',
			[RELATION_STATUS.FRIEND]: '是好友',
			[RELATION_STATUS.BLOCKED]: '已拉黑',
			[RELATION_STATUS.DELETED]: '已删除'
		};
		return statusMap[status] || '未知关系状态';
	}
	// FriendService 类中新增：单个发送好友申请
	/**
	 * @param {Object} params userId，friendUserId,applyMsg='',remarkName=''
	 * 
	 */
	async applyAddFriend(params) {
		const {
			userId,
			friendUserId,
			applyMsg = '',
			remarkName = ''
		} = params;
		console.log(params);

		// 1. 参数校验
		this.validateParams(params, ['userId', 'friendUserId']);
		if (userId === friendUserId) {
			throw new Error('不能添加自己为好友');
		}

		// 2. 查询当前用户与目标用户的已有关系
		const statusMap = await this.batchCheckRelationStatus(userId, [friendUserId]);
		const myStatus = statusMap.get(friendUserId);

		// 如果已是好友，直接返回提示，无需重复添加
		if (myStatus === 1) {
			return {
				success: false,
				message: `${this.getStatusText(myStatus)}，无需重复添加`
			};
		}

		// 3. 查询目标用户是否存在
		const friendUserRes = await this.userCollection
			.where({
				userId: friendUserId
			})
			.field({
				userId: 1
			})
			.get();
		if (friendUserRes.data.length === 0) {
			return {
				success: false,
				message: '目标用户不存在'
			};
		}

		// 4. 准备关系数据（用于更新或创建）
		const now = Date.now();
		const relationData = {
			remarkName,
			relationStatus: RELATION_STATUS.APPLYING, // 统一设置为申请状态
			applyTime: now,
			applyMsg,
			updateTime: now,
			deleteFlag: false
		};

		// 5. 判断是更新已有关系还是创建新关系
		let operationResult;
		if (myStatus !== undefined) {
			// 5.1 已有关系（申请中、已拉黑等），执行更新操作
			console.log(`发现已有关系状态: ${myStatus}，执行更新操作`);

			// 更新我对对方的关系
			const updateRes1 = await this.relationCollection
				.where({
					userId,
					friendUserId
				})
				.update(relationData);

			// 更新对方对我的关系
			const updateRes2 = await this.relationCollection
				.where({
					userId: friendUserId,
					friendUserId: userId
				})
				.update({
					...relationData,
					remarkName: '' // 对方的备注名由对方自己设置，这里清空
				});

			// 检查两条记录是否都更新成功
			if (updateRes1.updated > 0 && updateRes2.updated > 0) {
				operationResult = {
					success: true
				};
			} else {
				operationResult = {
					success: false,
					message: '更新好友关系失败'
				};
			}
		} else {
			// 5.2 无关系记录，执行创建操作（双向关系）
			console.log('无已有关系，执行创建操作');
			const relations = [{
					userId,
					friendUserId,
					...relationData,
					createTime: now
				},
				{
					userId: friendUserId,
					friendUserId: userId,
					...relationData,
					remarkName: '', // 对方的备注名留空
					createTime: now
				}
			];

			const addRes = await this.relationCollection.add(relations);
			if (addRes.ids.length === 2) {
				operationResult = {
					success: true
				};
			} else {
				operationResult = {
					success: false,
					message: '好友申请发送失败'
				};
			}
		}

		if (!operationResult.success) {
			return operationResult;
		}

		// 6. 发送好友申请通知
		const fromUserRes = await this.userCollection
			.where({
				userId
			})
			.field({
				nicName: 1
			})
			.get();
		const fromUserName = fromUserRes.data[0]?.nicName || '未知用户';

		await this.noticeCollection.add({
			userId: friendUserId,
			fromUserId: userId,
			fromUserName,
			noticeType: 'friend_apply',
			content: applyMsg || '请求添加你为好友',
			createTime: now,
			read: false
		});
		uniCloud.callFunction({
			name: 'web',
			data: {
				type:"friend_apply",
				toUserId: friendUserId,
				fromUserId: userId,
				applyMsg: applyMsg
			}
		})




		return {
			success: true,
			message: myStatus !== undefined ? '好友申请已重新发送' : '好友申请已发送'
		};
	}

	// 批量查询关系状态（不变）
	async batchCheckRelationStatus(userId, friendUserIds) {
		if (!friendUserIds.length) return new Map();
		const res = await this.relationCollection
			.where({
				userId,
				friendUserId: dbCmd.in(friendUserIds)
			})
			.limit(10000)
			.field({
				friendUserId: 1,
				relationStatus: 1
			})
			.get();
		console.log('好友关系++++++++++', res);
		const statusMap = new Map();
		res.data.forEach(item => statusMap.set(item.friendUserId, item.relationStatus));
		return statusMap;
	}

	// 批量查询对方关系状态（不变）
	async batchCheckPeerRelationStatus(userId, friendUserIds) {
		if (!friendUserIds.length) return new Map();
		const res = await this.relationCollection
			.where({
				userId: dbCmd.in(friendUserIds),
				friendUserId: userId
			})
			.field({
				userId: 1,
				relationStatus: 1
			})
			.limit(10000)
			.get();
		console.log('好友关系。。。。。。', res);
		const peerStatusMap = new Map();
		res.data.forEach(item => peerStatusMap.set(item.userId, item.relationStatus));
		return peerStatusMap;
	}

	// 分批次发送好友申请（不变，已正确用 user.userId）
	async batchSendFriendApply({
		user,
		contactList,
		userTelToIdMap,
		batchSize = 20
	}) {
		const applyResult = {
			successCount: 0,
			failCount: 0,
			failedDetails: [],
			successFriends: [],
			successFriendUserIds: []
		};

		// 步骤1：筛选好友ID（去重+排除自己）
		let friendUserIds = contactList
			.map(c => userTelToIdMap.get(c.telephone))
			.filter(friendId => friendId && friendId !== user.userId);
		const uniqueFriendIds = [...new Set(friendUserIds)];
		if (friendUserIds.length !== uniqueFriendIds.length) {
			const duplicateIds = friendUserIds.filter((id, index) => friendUserIds.indexOf(id) !== index);
			console.warn(`发现重复的 friendUserId：${[...new Set(duplicateIds)]}`);
			friendUserIds = uniqueFriendIds;
		}

		if (friendUserIds.length === 0) {
			console.log('无需要处理的好友ID（已排除自己或重复ID）');
			return applyResult;
		}

		// 步骤2：建立映射关系
		const friendIdToTelMap = new Map();
		const friendIdToDisplayNameMap = new Map();
		const telToDisplayNameMap = new Map();
		contactList.forEach(c => {
			if (c.telephone && c.displayName) telToDisplayNameMap.set(c.telephone, c.displayName);
		});
		for (const [tel, friendId] of userTelToIdMap.entries()) {
			if (friendUserIds.includes(friendId)) {
				friendIdToTelMap.set(friendId, tel);
				const displayName = telToDisplayNameMap.get(tel) || `联系人${tel.slice(-4)}`;
				friendIdToDisplayNameMap.set(friendId, displayName);
			}
		}
		console.log(`成功建立 ${friendIdToDisplayNameMap.size} 个好友ID与displayName的映射`);

		// 步骤3：查询已存在关系
		const existingRelations = await this.relationCollection
			.where({
				userId: user.userId,
				friendUserId: dbCmd.in(friendUserIds)
			})
			.limit(10000)
			.field({
				friendUserId: 1
			})
			.get();
		const existingFriendIds = new Set(existingRelations.data.map(r => r.friendUserId));
		const needCreateIds = friendUserIds.filter(id => !existingFriendIds.has(id));
		console.log(`需要创建的好友关系数：${needCreateIds.length} 对（已排除 ${existingFriendIds.size} 对已存在关系）`);

		if (needCreateIds.length === 0) {
			console.log('没有需要创建的好友关系');
			return applyResult;
		}

		// 步骤4：分批次创建记录
		const batches = [];
		for (let i = 0; i < needCreateIds.length; i += batchSize) batches.push(needCreateIds.slice(i, i +
			batchSize));
		console.log(`共分成 ${batches.length} 个批次处理，每批 ${batchSize} 个好友`);

		for (const batchFriendUserIds of batches) {
			const relations = [];
			const now = Date.now();
			batchFriendUserIds.forEach(friendId => {
				const remarkName = friendIdToDisplayNameMap.get(friendId) || `联系人${friendId.slice(-4)}`;
				const friendUserTel = friendIdToTelMap.get(friendId) || ''; // 加默认值避免字段缺失
				// 当前用户→好友
				relations.push({
					userId: user.userId,
					friendUserId: friendId,
					friendUserTel,
					remarkName,
					relationStatus: RELATION_STATUS.FRIEND,
					applyTime: now,
					applyMsg: '来自通讯录好友',
					createTime: now,
					updateTime: now,
					deleteFlag: false
				});
				// 好友→当前用户
				relations.push({
					userId: friendId,
					friendUserId: user.userId,
					friendUserTel: user.userTel || '', // 加默认值避免字段缺失
					remarkName: '',
					relationStatus: RELATION_STATUS.FRIEND,
					applyTime: now,
					applyMsg: '来自通讯录好友',
					createTime: now,
					updateTime: now,
					deleteFlag: false
				});
			});

			try {
				console.log(`处理批次：${batchFriendUserIds.length} 个好友，组装关系记录 ${relations.length} 条`);
				const res = await this.relationCollection.add(relations);
				if (res.ids.length === relations.length) {
					applyResult.successCount += batchFriendUserIds.length;
					applyResult.successFriends.push(...batchFriendUserIds.map(id => ({
						userId: id,
						telephone: friendIdToTelMap.get(id)
					})));
					console.log(`批次添加成功：${batchFriendUserIds.length} 对好友，插入 ${res.ids.length} 条记录`);
				} else {
					applyResult.failCount += batchFriendUserIds.length;
					applyResult.failedDetails.push(...batchFriendUserIds.map(id => ({
						userId: id,
						telephone: friendIdToTelMap.get(id),
						error: '部分插入失败（实际插入数与预期不符）'
					})));
					console.warn(`批次添加警告：预期插入 ${relations.length} 条，实际插入 ${res.ids.length} 条`);
				}
				await new Promise(resolve => setTimeout(resolve, 100));
			} catch (error) {
				console.error(`批次 ${batchFriendUserIds} 添加失败：`, error.message);
				applyResult.failCount += batchFriendUserIds.length;
				let errorMsg = error.message;
				if (errorMsg.includes('duplicate key')) errorMsg = '好友关系已存在';
				else if (errorMsg.includes('EMFILE')) errorMsg = '系统连接数超限';
				else if (errorMsg.includes('timeout')) errorMsg = '数据库请求超时';
				applyResult.failedDetails.push(...batchFriendUserIds.map(id => ({
					userId: id,
					telephone: friendIdToTelMap.get(id),
					error: errorMsg
				})));
				// 拆分重试
				if (errorMsg.includes('EMFILE') || errorMsg.includes('duplicate key') || errorMsg.includes(
						'timeout')) {
					console.log(`拆分批次重试：当前批次 ${batchFriendUserIds.length} 个，拆分为每批 10 个`);
					const retryBatchSize = 10;
					for (let j = 0; j < batchFriendUserIds.length; j += retryBatchSize) {
						const retryIds = batchFriendUserIds.slice(j, j + retryBatchSize);
						await this.retryAddRelations({
							user,
							retryIds,
							now,
							applyResult,
							friendIdToDisplayNameMap,
							friendIdToTelMap
						});
					}
				}
			}
		}
		return applyResult;
	}

	/**
	 * 重试添加好友关系（保留新函数，删除旧重复函数）
	 */
	async retryAddRelations({
		user,
		retryIds,
		now,
		applyResult,
		friendIdToDisplayNameMap,
		friendIdToTelMap
	}) {
		const existingRes = await this.relationCollection
			.where({
				userId: user.userId,
				friendUserId: dbCmd.in(retryIds)
			})
			.limit(10000)
			.field({
				friendUserId: 1
			})
			.get();
		const existingIds = new Set(existingRes.data.map(r => r.friendUserId));
		const realRetryIds = retryIds.filter(id => !existingIds.has(id));

		if (realRetryIds.length === 0) {
			console.log(`重试批次：${retryIds.length} 个好友关系已存在，无需重试`);
			return;
		}

		// 组装重试记录（加默认值）
		const retryRelations = [];
		realRetryIds.forEach(friendId => {
			const remarkName = friendIdToDisplayNameMap.get(friendId) || `联系人${friendId.slice(-4)}`;
			const friendUserTel = friendIdToTelMap.get(friendId) || '';
			// 当前用户→好友
			retryRelations.push({
				userId: user.userId,
				friendUserId: friendId,
				friendUserTel,
				remarkName,
				relationStatus: RELATION_STATUS.APPLYING,
				applyTime: now,
				applyMsg: '来自通讯录好友',
				createTime: now,
				updateTime: now,
				deleteFlag: false
			});
			// 好友→当前用户（修复：friendUserId 用 user.userId，加默认值）
			retryRelations.push({
				userId: friendId,
				friendUserId: user.userId,
				friendUserTel: user.userTel || '',
				remarkName: '',
				relationStatus: RELATION_STATUS.APPLYING,
				applyTime: now,
				applyMsg: '来自通讯录好友',
				createTime: now,
				updateTime: now,
				deleteFlag: false
			});
		});

		try {
			console.log(`重试批次：处理 ${realRetryIds.length} 个好友，组装记录 ${retryRelations.length} 条`);
			const res = await this.relationCollection.add(retryRelations);
			if (res.ids.length === retryRelations.length) {
				applyResult.successCount += realRetryIds.length;
				applyResult.failCount = Math.max(0, applyResult.failCount - realRetryIds.length);
				applyResult.successFriends.push(...realRetryIds.map(id => ({
					userId: id,
					telephone: friendIdToTelMap.get(id)
				})));
				console.log(`重试成功：${realRetryIds.length} 对好友，remarkName和手机号已同步`);
			} else {
				console.warn(`重试警告：预期添加 ${retryRelations.length} 条，实际插入 ${res.ids.length} 条`);
			}
		} catch (retryError) {
			console.error(`重试失败：${realRetryIds.length} 对好友，错误：`, retryError.message);
			const errorMsg = retryError.message.includes('duplicate key') ? '好友关系已存在' : retryError.message;
			applyResult.failedDetails.push(...realRetryIds.map(id => ({
				userId: id,
				telephone: friendIdToTelMap.get(id),
				error: `重试失败: ${errorMsg}`
			})));
		}
	}

	// 数据清洗与去重（不变）
	cleanAndDeduplicateContacts(contacts) {
		const contactMap = new Map();
		contacts.forEach(item => {
			const tel = String(item.telephone || '').replace(/\D/g, '');
			if (tel && /^1\d{10}$/.test(tel)) {
				if (!contactMap.has(tel)) {
					contactMap.set(tel, {
						telephone: tel,
						displayName: item.displayName || `联系人${tel.slice(-4)}`
					});
				}
			}
		});
		return Array.from(contactMap.values());
	}

	/**
	 * 批量处理通讯录（修复 userId 引用错误）
	 */
	async batchProcessContacts(user, contacts) {
		if (!Array.isArray(contacts)) throw new Error('参数错误：contact 必须是数组');

		// 1. 数据清洗
		const uniqueContacts = this.cleanAndDeduplicateContacts(contacts);
		const totalContacts = uniqueContacts.length;
		if (totalContacts === 0) {
			return {
				success: true,
				message: '通讯录中无有效手机号',
				data: {
					totalContacts: 0,
					registeredCount: 0,
					newlyRegisteredCount: 0,
					friendApplySuccessCount: 0,
					friendApplyFailCount: 0
				}
			};
		}

		const uniqueTels = uniqueContacts.map(c => c.telephone);
		let registeredUsers = [];
		let newlyRegisteredCount = 0;
		const userTelToIdMap = new Map();

		try {
			// 2. 批量查询已注册用户
			const registeredRes = await this.userCollection
				.where({
					userTel: dbCmd.in(uniqueTels)
				})
				.field({
					userId: 1,
					userTel: 1
				})
				.limit(10000)
				.get();
			registeredUsers = registeredRes.data;
			registeredUsers.forEach(u => userTelToIdMap.set(u.userTel, u.userId));
			console.log(`查询到已注册用户：${registeredUsers.length} 个`);

			// 3. 批量注册新用户
			const unregisteredContacts = uniqueContacts.filter(c => !userTelToIdMap.has(c.telephone));
			console.log("还未注册的用户数：", unregisteredContacts.length);
			if (unregisteredContacts.length > 0) {
				const newUsers = unregisteredContacts.map(c => ({
					userId: generateString(c.telephone),
					userTel: c.telephone,
					nicName: generateString(c.telephone),
					registerType: 'contact_sync',
					registerTime: Date.now(),
					avatar: ''
				}));
				const batchSize = 500;
				let realRegisteredCount = 0;
				for (let i = 0; i < newUsers.length; i += batchSize) {
					const batch = newUsers.slice(i, i + batchSize);
					const addRes = await this.userCollection.add(batch);
					realRegisteredCount += addRes.ids.length;
				}
				newlyRegisteredCount = realRegisteredCount;
				newUsers.forEach(u => userTelToIdMap.set(u.userTel, u.userId));
				console.log(`成功注册新用户：${newlyRegisteredCount} 个（目标：${unregisteredContacts.length} 个）`);
			}

			// 4. 分批次发送好友申请
			const applyResult = await this.batchSendFriendApply({
				user,
				contactList: uniqueContacts,
				userTelToIdMap,
				batchSize: 20
			});

			// 5. 异步发送通知（修复 userId 引用）
			console.log("+++++++++++", applyResult.successFriends);
			const successUserIds = applyResult.successFriends.map(item => item.userId);
			if (successUserIds.length > 0) {
				let fromUserName = '未知用户';
				try {
					// 修复：查询发送者信息时用 user.userId
					const fromUserRes = await this.userCollection
						.where({
							userId: user.userId
						})
						.field({
							nicName: 1
						})
						.get();
					// 修复：nicName 拼写（原代码写的 nickName）
					fromUserName = fromUserRes.data[0]?.nicName || fromUserName;
				} catch (err) {
					console.error('批量查询发送者信息失败：', err.message);
				}
				const batchSize = 10;
				for (let i = 0; i < successUserIds.length; i += batchSize) {
					const batchUids = successUserIds.slice(i, i + batchSize);
					const noticeList = batchUids.map(uid => ({
						userId: uid,
						fromUserId: user.userId, // 修复：用 user.userId
						fromUserName: fromUserName,
						noticeType: 'friend_apply',
						content: '来自通讯录好友',
						createTime: Date.now(),
						read: false
					}));
					try {
						await this.noticeCollection.add(noticeList);
						console.log(`成功发送第 ${Math.floor(i / batchSize) + 1} 批通知，共 ${batchUids.length} 条`);
					} catch (err) {
						console.error(`第 ${Math.floor(i / batchSize) + 1} 批通知发送失败：`, err.message);
					}
					await new Promise(resolve => setTimeout(resolve, 50));
				}
			}

			// 返回完整结果（补充缺失的统计字段）
			return {
				success: true,
				data: {
					totalContacts,
					registeredCount: registeredUsers.length + newlyRegisteredCount,
					newlyRegisteredCount,
					friendApplySuccessCount: applyResult.successCount,
					friendApplyFailCount: applyResult.failCount,
					failedDetails: applyResult.failedDetails
				}
			};
		} catch (error) {
			console.error('通讯录同步失败：', error);
			throw new Error(`处理失败：${error.message}`);
		}
	}

	// 申请回应的处理方法（保持不变，已适配集合名称）
	async handleApply(params) {
		const {
			userId,
			friendUserId,
			agree
		} = params;
		this.validateParams(params, ['userId', 'friendUserId', 'agree']);
		if (typeof agree !== 'boolean') {
			throw new Error('参数错误：agree 必须是布尔值');
		}

		const relationRes = await this.relationCollection
			.where({
				userId,
				friendUserId,
				relationStatus: RELATION_STATUS.APPLYING
			})
			.get();
		if (!relationRes.data.length) {
			return {
				success: false,
				message: '申请已过期或已处理'
			};
		}

		const now = Date.now();
		const updateData = agree ? {
			relationStatus: RELATION_STATUS.FRIEND,
			agreeTime: now,
			updateTime: now
		} : {
			relationStatus: RELATION_STATUS.DELETED,
			updateTime: now,
			deleteFlag: true
		};

		await Promise.all([
			this.relationCollection.where({
				userId,
				friendUserId
			}).update(updateData),
			this.relationCollection.where({
				userId: friendUserId,
				friendUserId: userId
			}).update(updateData)
		]);

		const action = agree ? '同意' : '拒绝';
		return {
			success: true,
			message: `${action}成功`
		};
	}

	async blockFriend(params) {
		const {
			userId,
			friendUserId,
			isBlock
		} = params;
		this.validateParams(params, ['userId', 'friendUserId', 'isBlock']);
		if (typeof isBlock !== 'boolean') {
			throw new Error('参数错误：isBlock 必须是布尔值');
		}

		const statusMap = await this.batchCheckRelationStatus(userId, [friendUserId]);
		const status = statusMap.get(friendUserId) || null;
		if (status !== RELATION_STATUS.FRIEND && !isBlock) {
			throw new Error('不是好友关系，无法取消拉黑');
		}
		if (status === RELATION_STATUS.BLOCKED && isBlock) {
			return {
				success: false,
				message: '对方已被拉黑'
			};
		}

		const updateData = {
			relationStatus: isBlock ? RELATION_STATUS.BLOCKED : RELATION_STATUS.FRIEND,
			updateTime: Date.now()
		};

		await Promise.all([
			this.relationCollection.where({
				userId,
				friendUserId
			}).update(updateData),
			this.relationCollection.where({
				userId: friendUserId,
				friendUserId: userId
			}).update(updateData)
		]);

		const action = isBlock ? '拉黑' : '取消拉黑';
		return {
			success: true,
			message: `${action}成功`
		};
	}

	async deleteFriend(params) {
		const {
			userId,
			friendUserId
		} = params;
		this.validateParams(params, ['userId', 'friendUserId']);

		const statusMap = await this.batchCheckRelationStatus(userId, [friendUserId]);
		const status = statusMap.get(friendUserId) || null;
		if (![RELATION_STATUS.FRIEND, RELATION_STATUS.BLOCKED].includes(status)) {
			throw new Error('无此好友关系');
		}

		const now = Date.now();
		const updateData = {
			relationStatus: RELATION_STATUS.DELETED,
			deleteFlag: true,
			updateTime: now
		};

		await Promise.all([
			this.relationCollection.where({
				userId,
				friendUserId
			}).update(updateData),
			this.relationCollection.where({
				userId: friendUserId,
				friendUserId: userId
			}).update(updateData)
		]);

		return {
			success: true,
			message: '删除成功'
		};
	}

	async isFriend(params) {
		const {
			userId,
			targetUserId
		} = params;
		this.validateParams(params, ['userId', 'targetUserId']);
		if (userId === targetUserId) {
			throw new Error('参数错误：不能查询自己与自己的关系');
		}

		const statusMap = await this.batchCheckRelationStatus(userId, [targetUserId]);
		const status = statusMap.get(targetUserId); // 直接获取状态，不做 falsy 判断

		if (status !== undefined) { // 用 undefined 判断是否存在关系
			return {
				success: true,
				data: {
					isFriend: status === RELATION_STATUS.FRIEND,
					status,
					statusText: this.getStatusText(status)
				}
			};
		}

		return {
			success: true,
			data: {
				isFriend: false,
				status: null,
				statusText: '无关系'
			}
		};
	}
	/**
	 * @param {Object} params userId必传，keyword,page,pageSize
	 * @returns {object} success,data
	 */

	async getFriendList(params) {
		try {
			const {
				userId,
				keyword = '',
				page = 1,
				pageSize = 30,
				targetId = null
			} = params;
			console.log('传进来的查询参数', JSON.stringify(params));
			this.validateParams(params, ['userId']);
			if (page < 1 || pageSize < 1) {
				throw new Error('参数错误：页码和每页数量必须大于0');
			}
			const skip = (page - 1) * pageSize;
			let searchStage = {
				userId: userId,
				relationStatus: {$in:[RELATION_STATUS.FRIEND,0]} ,
				deleteFlag: false,
			};
			if (keyword.trim()) {
				searchStage.$or = [{
						remarkName: {
							$regex: keyword,
							$options: 'i'
						}
					},
					// 注意：这里的 'friendInfo.nicName' 是你原始集合中的字段，如果不存在，可以去掉
					{
						friendUserTel: {
							$regex: keyword,
							$options: 'i'
						}
					}
				]
			} else if (targetId) {
				searchStage = {
					...searchStage,
					friendUserId: targetId
				}
			}
			console.log('查询参数结构', searchStage);
			const res = await this.relationCollection.aggregate().match(searchStage)
				.lookup({
					from: "linli-user", // 要关联的目标集合名称
					localField: "friendUserId", // 当前集合中用于匹配的字段（好友的ID）
					foreignField: "userId", // 目标集合（linli-user）中用于匹配的字段（用户ID）
					as: "friendDetail" // 将匹配到的用户信息存入这个新字段
				})
				.unwind({
					path: "$friendDetail",
					preserveNullAndEmptyArrays: true // 即使没有关联到用户（如数据不一致），也保留这条好友关系记录
				})
				.project({
					_id: 0, // 不返回关系记录的默认ID
					friendUserId: 1, // 好友用户ID
					remarkName: 1, // 备注名
					relationStatus: 1, // 关系状态
					friendUserTel: 1,
					friendDetail: 1

				})
				.skip(targetId ? 0 : skip).limit(targetId ? 1 : pageSize)

				.end();
            console.log("查到的好友",res);
			return {
				success: true,
				data: res.data || []
			}

		} catch (e) {
			return {
				success: false,
				message: '查找好友列表失败',

			}
		}

	}
	async getFriendGroups(params) {
		const {
			userId
		} = params;
		this.validateParams(params, ['userId']);

		const res = await db.collection('friend_group')
			.where({
				userId
			})
			.sort({
				sortOrder: 1
			})
			.get();

		return {
			success: true,
			data: res.data
		};
	}

	async checkCanSendMsg(params) {
		const {
			fromUid,
			toUid
		} = params;
		this.validateParams(params, ['fromUid', 'toUid']);

		const statusMap = await this.batchCheckRelationStatus(toUid, [fromUid]);
		if (statusMap.get(fromUid) === RELATION_STATUS.BLOCKED) {
			throw new Error('对方已将你拉黑，无法发送消息');
		}

		return {
			success: true,
			data: {
				canSend: true
			}
		};
	}
	// 完善：用手机号加好友（未注册则自动注册，对方状态为已申请）
	async addFriendByTelePhone(params) {
		const {
			user,
			telePhone,
			remarkName = '',
			applyMsg = ''
		} = params;

		// 1. 严格参数校验
		this.validateParams(params, ['user', 'telePhone']);
		if (!user?.userId) throw new Error('参数错误：用户ID不能为空');

		// 手机号格式校验（与现有通讯录清洗逻辑一致）
		const pureTel = String(telePhone).replace(/\D/g, '');
		if (!/^1[3-9]\d{9}$/.test(pureTel)) {
			throw new Error('参数错误：请输入有效的手机号');
		}

		// 2. 查询手机号对应的用户（判断是否已注册）
		let friendUserId = '';
		const userRes = await this.userCollection
			.where({
				userTel: pureTel
			})
			.field({
				userId: 1
			})
			.get();

		if (userRes.data.length > 0) {
			// 2.1 已注册：直接获取对方用户ID
			friendUserId = userRes.data[0].userId;
			console.log(`手机号${pureTel}已注册，用户ID：${friendUserId}`);
		} else {
			// 2.2 未注册：自动注册新用户（复用通讯录注册逻辑）
			friendUserId = generateString(pureTel); // 用手机号生成唯一用户ID
			const now = Date.now();
			const newUser = {
				userId: friendUserId,
				userTel: pureTel,
				nicName: `用户${pureTel.slice(-4)}`, // 默认昵称（尾号4位）
				registerType: 'friend_apply', // 注册来源：好友申请
				registerTime: now,
				avatar: '', // 空头像（后续可让用户完善）
				deleteFlag: false
			};

			await this.userCollection.add(newUser);
			console.log(`手机号${pureTel}未注册，已自动注册新用户：${friendUserId}`);
		}

		// 3. 调用现有方法发送好友申请（自动处理关系创建/更新，状态为APPLYING）
		const applyResult = await this.applyAddFriend({
			userId: user.userId, // 当前发起申请的用户ID
			friendUserId: friendUserId, // 目标用户ID（注册/查询得到）
			remarkName: remarkName, // 给对方的备注
			applyMsg: applyMsg || `通过手机号${pureTel}添加你为好友` // 申请留言
		});

		// 4. 优化返回信息（明确告知是否触发自动注册）
		if (userRes.data.length === 0) {
			applyResult.message = `已向好友发送申请，请等待通过！`;
		}

		return applyResult;
	}
	/**
	 * 修改好友备注名
	 * @param {Object} params - 参数对象
	 * @param {string} params.userId - 当前用户ID（必填）
	 * @param {string} params.friendUserId - 目标好友ID（必填）
	 * @param {string} params.remarkName - 新备注名（必填，可传空字符串清空备注）
	 * @returns {Object} - 操作结果（success + message + 可选data）
	 */
	async editFriendRemarkName(params) {
		const {
			userId,
			friendUserId,
			remarkName
		} = params;
		console.log('修改好友备注参数：', params);

		// 1. 严格参数校验
		this.validateParams(params, ['userId', 'friendUserId', 'remarkName']);
		if (userId === friendUserId) {
			throw new Error('不能给自己设置备注');
		}

		// 2. 校验好友关系（必须是已添加的好友）
		const statusMap = await this.batchCheckRelationStatus(userId, [friendUserId]);
		const relationStatus = statusMap.get(friendUserId);

		if (relationStatus !== RELATION_STATUS.FRIEND) {
			return {
				success: false,
				message: relationStatus === null ?
					'无此好友关系，无法设置备注' :
					`当前关系为${this.getStatusText(relationStatus)}，仅好友可设置备注`
			};
		}

		// 3. 执行备注更新（仅更新当前用户→好友的单向记录）
		const now = Date.now();
		const updateResult = await this.relationCollection
			.where({
				userId: userId, // 当前用户ID（备注所有者）
				friendUserId: friendUserId, // 目标好友ID
				relationStatus: RELATION_STATUS.FRIEND, // 确保是好友关系
				deleteFlag: false // 排除已删除的关系
			})
			.update({
				remarkName: remarkName, // 新备注名（支持空字符串清空）
				updateTime: now // 更新时间戳
			});

		// 4. 校验更新结果
		if (updateResult.updated > 0) {
			return {
				success: true,
				message: remarkName ? `备注名更新为"${remarkName}"` : '备注名已清空',
				data: {
					friendUserId: friendUserId,
					remarkName: remarkName,
					updateTime: now
				}
			};
		} else {
			return {
				success: false,
				message: '备注更新失败（可能未找到对应好友关系或无变更）'
			};
		}
	}
}

// 导出云对象（保持原有调用方式兼容）
module.exports = {
	_before: async function() {
		this.friendService = new FriendService();
	},

	applyAddFriend: async function(params) {
		return this.friendService.applyAddFriend(params);
	},

	handleApply: async function(params) {
		return this.friendService.handleApply(params);
	},

	blockFriend: async function(params) {
		return this.friendService.blockFriend(params);
	},

	deleteFriend: async function(params) {
		return this.friendService.deleteFriend(params);
	},

	isFriend: async function(params) {
		console.log("参数检验是否好友", params);
		return this.friendService.isFriend(params);
	},

	getFriendList: async function(params) {
		return this.friendService.getFriendList(params);
	},

	getFriendGroups: async function(params) {
		return this.friendService.getFriendGroups(params);
	},

	checkCanSendMsg: async function(params) {
		return this.friendService.checkCanSendMsg(params);
	},

	uploadContactsToDB: async function(params) {
		const {
			user,
			contacts
		} = params
		if (!user && !user.userId) {
			throw new Error('用户ID不能为空')
		}

		return this.friendService.batchProcessContacts(user, contacts);
	},
	addFriendByTelePhone: async function(params) {
		return this.friendService.addFriendByTelePhone(params)


	},
	editFriendRemarkName: async function(parmas) {
		return this.friendService.editFriendRemarkName(parmas)
	}
};